package handles

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"tour-guide/models"
)

func Add(c *gin.Context) {

	title := c.PostForm("title")
	address := c.PostForm("address")
	price, _ := strconv.Atoi(c.PostForm("price"))

	if title == "" || address == "" || price == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}
	data := models.Travel{

		Title:   title,
		Address: address,
		Price:   price,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "添加成功",
	})
	return
}

func File(c *gin.Context) {

	file, _ := c.FormFile("file")
	if file.Size > 1024*1024*2 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "图片大小限制2M以内",
		})
		return
	}
	err := c.SaveUploadedFile(file, "./file/img"+file.Filename)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "上传文件失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "上传文件成功",
	})
	return
}
func Del(c *gin.Context) {
	id := c.PostForm("id")
	var travel models.Travel
	err := models.DB.Where("id=?", id).Delete(&travel).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"data": "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"data": "删除成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var travel []models.Travel
	models.DB.Offset(offset).Limit(size).Find(&travel)

	var total int64
	models.DB.Model(&models.Travel{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "成功",
		"data":  travel,
		"total": total,
	})
	return
}
